package net.wanho.study.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Author：汤小洋
 * Date：2023-12-11 9:35
 * Description：<描述>
 */
public class MyBatisUtil {

    private static ThreadLocal<SqlSession> local = new ThreadLocal<>();
    private static SqlSessionFactory factory;

    // 初始化SqlSessionFactory
    static{
        try {
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(MyBatisUtil.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            throw new ExceptionInInitializerError("MyBatisUtil初始化失败：" + e.getMessage());
        }
    }


    /**
     * 获取SqlSession对象
     */
    public static SqlSession getSession(){
        SqlSession session = local.get();
        if(session == null){
            session = factory.openSession();
            // session = factory.openSession(ExecutorType.BATCH); // Batch批处理模式
            local.set(session);
        }
        return session;
    }


    /**
     * 关闭资源
     */
    public static void close(){
        SqlSession session = local.get();
        if(session != null){
            session.close();
            local.remove();
        }
    }


    public static void main(String[] args) {

    }
}
